package Servlets.Admin;

import Utils.JjwtUtil;
import Utils.SqlCon;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author SDU德布罗煜
 * @Date 2021/8/11 18:53
 * @Description 获取列车线路时刻表
 * @Version 1.0
 */

@WebServlet("/admin/getRoutes")
public class GetRoutes extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter pw = resp.getWriter();
        String jwt = req.getHeader("Authorization");
        if (jwt == null || jwt.equals("Bearer null")) {
            pw.write("{\"code\": -1, \"data\":\"用户未登录\"}");
        } else {
            int jwtVer = JjwtUtil.vertify(jwt);
            if (jwtVer == 0) {
                Claims c = JjwtUtil.parseJWT(jwt);
                Connection conn = null;
                try {
                    String userId = c.getSubject();
                    conn = SqlCon.getInstance();
                    PreparedStatement ps = conn.prepareStatement("SELECT 1 FROM Admins WHERE user_id = ?");
                    ps.setString(1, userId);
                    ps.execute();
                    ResultSet rs = ps.getResultSet();
                    if (rs.next()) {
                        String train_id = req.getParameter("train");
                        ps = conn.prepareStatement("SELECT 1 FROM Trains WHERE train_id = ?");
                        ps.setString(1, train_id);
                        ps.execute();
                        rs = ps.getResultSet();
                        if (rs.next()) {
                            ps = conn.prepareStatement("SELECT station_name, stop_index, day_num, arrive_time, stop_time, distance FROM TrainStation WHERE train_id = ? ORDER BY stop_index ASC");
                            ps.setString(1, train_id);
                            ps.execute();
                            rs = ps.getResultSet();
                            List<Map> list = new ArrayList<>();
                            while (rs.next()) {
                                Map<String, Object> map = new HashMap<>();
                                map.put("index", rs.getInt("stop_index"));
                                map.put("station", rs.getString("station_name"));
                                map.put("arrive", rs.getString("arrive_time"));
                                map.put("stop", rs.getInt("stop_time"));
                                map.put("days", rs.getInt("day_num"));
                                map.put("distance", rs.getInt("distance"));
                                list.add(map);
                            }
                            pw.write("{\"code\":0, \"data\":" + JSON.toJSONString(list) + "}");
                        } else {
                            pw.write("{\"code\":-3, \"data\":\"该列车不存在！\"}");
                        }
                        if (conn != null) {
                            conn.close();
                        }
                    } else {
                        pw.write("{\"code\":-2, \"data\":\"权限不足\"}");
                    }
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException throwables) {
                    try {
                        conn.rollback();
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    pw.write("{\"code\":-3, \"data\":\"数据库错误\"}");
                }
            } else if (jwtVer == -1) {
                pw.write("{\"code\":-1, \"data\":\"非法token\"}");
            } else {
                pw.write("{\"code\":-1, \"data\":\"token过期\"}");
            }
        }
        pw.close();
    }
}
